<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-button :key="index" :type="item.color" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ invCode: record.invCode })">
          {{ record.invCode }}
        </a>
      </template>
      <!-- 勾选 -->
      <template #checkBox="{ record, column }">
        <a-checkbox :checked="record[column.dataIndex] == '1' ? true : false" />
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="产品码补打"
      @ok="handleModal"
      :width="1000"
    >
      <BasicTable @register="registerPuArrTable" @row-click="handlePuArrRowClick" />
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
    <PackForm @register="registerPackDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasInvBasInvList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, ref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useGo } from '/@/hooks/web/usePage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable } from '/@/components/Table';
  import { basInvDelete, uploadVideo, uploadPdf } from '/@/api/bas/inv/basInv';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicUpload } from '/@/components/Upload';
  import InputForm from './form.vue';
  import PackForm from './basInvPack/form.vue';
  import PrintModal from '/@/components/print/printModal.vue';
  import FormImport from './formImport.vue';

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  const { t } = useI18n('bas.inv.basInv');
  const { showMessage } = useMessage();
  const go = useGo();

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  let invCode = ref('');

  const actionColumn: BasicColumn = {
    width: 210, //操作按钮宽度
    actions: (record: Recordable) => {
      actionColumnData.value.forEach((item) => {
        if (item.title == '查看包装规格') {
          item.label = '查看包装规格';
          item.onClick = () => handlePickView({ invCode: record.invCode });
        }
        if (item.title == '添加包装规格') {
          item.label = '添加包装规格';
          item.onClick = () => handAddPack({ record });
        }
      });
      return actionColumnData.value;
    },
    // actions: (record: Recordable) => [
    //   {
    //     icon: 'clarity:timeline-line',
    //     title: t('详情配置'),
    //     onClick: handleDetails.bind(this, { cinvcode: record.cinvcode }),
    //     // auth: 'test:testData:edit',
    //   },
    // ],
  };

  const tableColumnsPrint: BasicColumn[] = [
    {
      title: t('存货编码'),
      dataIndex: 'invCode',
      key: 'a.inv_code',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'invName',
      key: 'a.inv_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('批次'),
      dataIndex: 'cbatch',
      key: 'a.cbatch',
      sorter: true,
      width: 100,
      align: 'center',
      editable: true,
      edit: true,
      editRow: true,
      editComponent: 'Input',
      editComponentProps: {
        maxlength: 50,
      },
      editRule: true,
    },
  ];

  const [registerPuArrTable, invPrintTable] = useTable({
    columns: tableColumnsPrint,
    rowKey: 'id',
    pagination: false,
    bordered: true,
  });

  const [registerTable, { reload, setProps, getForm, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  const [registerModal, { openModal, closeModal }] = useModal();

  onMounted(async () => {
    const res = await listSet({ viewCode: 'bas_inv_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey == 'btnPackImport') {
        item.do = () => handlePackImport({});
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  const [registerPackDrawer, { openDrawer: openPackDrawer }] = useDrawer();

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        'basInvCls.code': props.treeCode,
        'basInv.invCls.treeName': props.treeName,
      });
      reload();
    },
  );

  function handleDetails(record: Recordable) {
    invCode.value = record.invCode;
    // cversion.value = record.cversion;
    // title.value = `首页配置 （版本号：${record.cversion}）`;
    openAppsetDetailsDrawer(true);
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handlePuArrRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function getInvList() {
    let invValid = true;
    let invList: Recordable[] = [];
    for (const record of invPrintTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        invValid = false;
      }
      invList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of invPrintTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      invList.push({
        ...record,
        status: '1',
      });
    }
    if (!invValid) {
      throw { errorFields: [{ name: ['invList'] }] };
    }
    return invList;
  }

  async function handleDelete(record: Recordable) {
    const res = await basInvDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 补打：批次
  async function handlePrint() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    await openModal(true, {});
    invPrintTable.setTableData(arr);
  }

  // 产品码补打
  async function handleModal() {
    const data = await getInvList();
    let params = {
      ids: '',
      title: '产品码补打',
      height: '0.9',
      width: '0.9',
      fileName: '产品码补打',
    };
    params.ids = data.map((item) => `${item.invCode}-${item.cbatch}`).join(',');
    openPrintModal(true, params);
    closeModal();
    invPrintTable.setTableData([]);
  }

  // 包装规格导入
  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/bas/inv/pack/basInvPack/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  // 添加包装规格
  async function handAddPack(record: Recordable) {
    openPackDrawer(true, record);
  }

  // 查看包装规格
  function handlePickView(record: Recordable) {
    go({ path: '/bas/inv/basInv/basInvPack/list', query: { invCode: record.invCode } });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handlePackImport() {
    importModal(true, {});
  }

  function handleSuccess() {
    reload();
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
